import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Home from '@/views/home/index.vue'
import Publish from '@/views/publish/index.vue'
import Article from '@/views/article/index.vue'
import Layout from '@/views/layout/index.vue'
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        // alias: '/',
        component: Home
      },
      {
        path: '/publish',
        component: Publish
      },
      {
        path: '/article',
        component: Article
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (getItem()) {
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
  Nprogress.done()
})
// 后置守卫

router.afterEach((to, from) => {
  Nprogress.done()
  console.log('afterEach', to, from)
})
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
